// Fill in your client ID and client secret that you obtained
// while registering the application
const clientID = '7c3f4f6dcdd01bd2f9c0'
const clientSecret = '93f7ce3d462a76a6350932ec6ae4f12337b7a452'

const Koa = require('koa')
const path = require('path')
const serve = require('koa-static')
const route = require('koa-route')
const axios = require('axios')

const app = new Koa()

const main = serve(path.join(__dirname + '/public'))

const oauth = async (ctx) => {
	const requestToken = ctx.request.query.code
	console.log('authorization code:', requestToken)

	const tokenResponse = await axios({
		method: 'post',
		url:
			'https://github.com/login/oauth/access_token?' +
			`client_id=${clientID}&` +
			`client_secret=${clientSecret}&` +
			`code=${requestToken}`,
		headers: {
			accept: 'application/json'
		}
	})

	console.log(tokenResponse, 'tokenResponse-----------')
	const accessToken = tokenResponse.data.access_token
	console.log(`access token: ${accessToken}`)

	const result = await axios({
		method: 'get',
		url: `https://api.github.com/user`,
		headers: {
			accept: 'application/json',
			Authorization: `token ${accessToken}`
		}
	})
	console.log(result.data)
	const name = result.data.login
	const avatar = result.data.avatar_url

	ctx.response.redirect(`/welcome.html?name=${name}&avatar=${avatar}`)
}

app.use(main)
app.use(route.get('/oauth/redirect', oauth))

app.listen(3000, () => {
	console.log(`http://localhost:3000`)
})
